package com.xlinur.android.moviecatalog;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Spinner;
import android.widget.Toast;
//TODO удобное добавление размера
public class MovieEditor extends Activity {
	private static String DIVIDER = ",";
	public static String mTitle;
	public static Map<String,String> mInfo = null;
	private static String strNone;
	protected static Button mButtonSave;
	protected static Button mButtonGrab;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		strNone = getResources().getString(R.string.none);
		setContentView(R.layout.movie_editor);
		mButtonSave = (Button) findViewById(R.id.editButtonSave);
		mButtonSave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				onSaveButtonClicked();
			}
		});
		Button buttonCancel = (Button) findViewById(R.id.editButtonCancel);
		buttonCancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		mButtonGrab = (Button) findViewById(R.id.editButtonGrab);
		mButtonGrab.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent editorActivity = new Intent(getBaseContext(), MovieGrab.class);
				EditText field = (EditText) findViewById(R.id.editEditText_title);
				mTitle = field.getText().toString();
				startActivity(editorActivity);
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(getBaseContext());
		String grabber = prefs.getString("prefGrabber", "imdb.com");
		mButtonGrab.setText(getResources().getString(R.string.button_grab).replace("{1}", grabber));
		if (mInfo==null){
			fillForm();
		} else {
			fillMovieInfo();
			mInfo=null;
		}
	}
	
	private EditText getFieldByName(String fieldName){
		int fieldId = 0;
		EditText field = null;
		try {
			fieldId = R.id.class.getField(
					"editEditText_" + fieldName).getInt(null);
		} catch (IllegalArgumentException e) {
		} catch (SecurityException e) {
		} catch (IllegalAccessException e) {
		} catch (NoSuchFieldException e) {
		}
		if (fieldId > 0) {
			field = (EditText) findViewById(fieldId);
		}
		return field;
	}

	private void fillMovieInfo() {
		@SuppressWarnings("rawtypes")
		Set set = mInfo.entrySet();
		@SuppressWarnings("rawtypes")
		Iterator it = set.iterator();
		
		while(it.hasNext()){
			@SuppressWarnings("unchecked")
			Map.Entry<String, String> entry = (Entry<String, String>)it.next();
			EditText field = this.getFieldByName(entry.getKey());
			if (field != null) {
				field.setText(entry.getValue());
			}
		}
		
		if (mInfo.containsKey("genre")){
			MultiAutoCompleteTextView genresMultiAuto = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoEditText_genre);
			genresMultiAuto.setText(mInfo.get("genre"));
		}
	}
	
	private void fillForm() {
		Map<String,String> columns = null;
		if (!MovieList.mCurId.equals("")) {
			this.setTitle(R.string.title_movie_edit);
			mButtonSave.setText(R.string.button_save);
			columns = MovieCatalog.db.getMovie(MovieList.mCurId);
		} else {
			this.setTitle(R.string.title_movie_add);
			mButtonSave.setText(R.string.button_add);
			columns = MovieCatalog.db.getEmptyMovie();
		}
		@SuppressWarnings("rawtypes")
		Set set = columns.entrySet();
		@SuppressWarnings("rawtypes")
		Iterator it = set.iterator();
		
		while(it.hasNext()){
			@SuppressWarnings("unchecked")
			Map.Entry<String, String> entry = (Entry<String, String>)it.next();
			EditText field = this.getFieldByName(entry.getKey());
			if (field != null) {
				field.setText(entry.getValue());
			}
		}
		
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());

		String[] line;
		int count;
		int position;
		String pref;
		Spinner videoSpinner = (Spinner) findViewById(R.id.spinner_video);
		pref = prefs.getString("prefVideos",
				getResources().getString(R.string.videos));
		line = (strNone + DIVIDER + pref).split(DIVIDER);
		count = line.length;
		position = 0;
		for (int i = 0; i < count; i++) {
			line[i] = line[i].trim();
			if (line[i].equals(columns.get("video"))) {
				position = i;
			}
		}
		ArrayAdapter<String> videoAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, line);
		videoAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		videoSpinner.setAdapter(videoAdapter);
		videoSpinner.setSelection(position);

		Spinner audioSpinner = (Spinner) findViewById(R.id.spinner_audio);
		pref = prefs.getString("prefAudios",
				getResources().getString(R.string.audios));
		line = (strNone + DIVIDER + pref).split(DIVIDER);
		count = line.length;
		position = 0;
		for (int i = 0; i < count; i++) {
			line[i] = line[i].trim();
			if (line[i].equals(columns.get("audio"))) {
				position = i;
			}
		}
		ArrayAdapter<String> audioAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, line);
		audioAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		audioSpinner.setAdapter(audioAdapter);
		audioSpinner.setSelection(position);

		MultiAutoCompleteTextView genresMultiAuto = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoEditText_genre);
		pref = prefs.getString("prefGenres",
				getResources().getString(R.string.genres));
		line = (strNone + DIVIDER + pref).split(DIVIDER);
		for (int i = 0; i < count; i++) {
			line[i] = line[i].trim();
		}
		ArrayAdapter<String> genresAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, line);
		genresMultiAuto.setAdapter(genresAdapter);
		genresMultiAuto
				.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
		genresMultiAuto.setText(columns.get("genre"));
	}

	private void onSaveButtonClicked() {
		boolean status = false;
		Map<String,String> columns = null;
		if (!MovieList.mCurId.equals("")) {
			this.setTitle(R.string.title_movie_edit);
			mButtonSave.setText(R.string.button_save);
			columns = MovieCatalog.db.getMovie(MovieList.mCurId);
		} else {
			this.setTitle(R.string.title_movie_add);
			mButtonSave.setText(R.string.button_add);
			columns = MovieCatalog.db.getEmptyMovie();
		}
		@SuppressWarnings("rawtypes")
		Set set = columns.entrySet();
		@SuppressWarnings("rawtypes")
		Iterator it = set.iterator();
		
		while(it.hasNext()){
			@SuppressWarnings("unchecked")
			Map.Entry<String, String> entry = (Entry<String, String>) it.next();
			EditText field = this.getFieldByName(entry.getKey());
			if (field != null) {
				columns.put(entry.getKey(), field.getText().toString());
			} else {
				columns.put(entry.getKey(), "");
			}
		}
		
		String value;
		Object item;

		item = ((Spinner) findViewById(R.id.spinner_video)).getSelectedItem();
		if (item != null) {
			value = item.toString();
			if (!value.equals(strNone)) {
				columns.put("video", value);
			}
		}

		item = ((Spinner) findViewById(R.id.spinner_audio)).getSelectedItem();
		if (item != null) {
			value = item.toString();
			if (!value.equals(strNone)) {
				columns.put("audio", value);
			}
		}

		value = ((MultiAutoCompleteTextView) findViewById(R.id.multiAutoEditText_genre))
				.getText().toString();
		if (value != null) {
			value = value.trim();
			if (value.endsWith(DIVIDER)) {
				value = value.substring(0, value.length() - 1);
			}
		}
		columns.put("genre", value);

		if (!MovieList.mCurId.equals("")) {
			if (MovieCatalog.db.updateMovie(MovieList.mCurId, columns) == 1) {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.message_movie_update_success)
								.replace("{1}", columns.get("title")),
						MovieCatalog.MESSAGE_TIME).show();
				status = true;
			} else {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.message_movie_update_fail).replace(
								"{1}", columns.get("title")), MovieCatalog.MESSAGE_TIME)
						.show();
			}
		} else {
			if (MovieCatalog.db.insertMovie(columns) != -1) {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.message_movie_add_success).replace(
								"{1}", columns.get("title")), MovieCatalog.MESSAGE_TIME)
						.show();
				status = true;
			} else {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.message_movie_add_fail).replace(
								"{1}", columns.get("title")), MovieCatalog.MESSAGE_TIME)
						.show();
			}
		}
		if (status) {
			finish();
		}
	}
}
